﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI.Adapters;

namespace FormsAuthWeb.Utils
{
    public class CustomPageAdapter : PageAdapter
    {
        private static readonly Hashtable methodTable = Hashtable.Synchronized(new Hashtable());

        private static MethodInvokeInfo[] GetMethodInfo(Type type)
        {
            MethodInvokeInfo[] array = CustomPageAdapter.methodTable[type.AssemblyQualifiedName] as MethodInvokeInfo[];
            if (array == null)
            {
                array = (from m in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)
                         let a = m.GetCustomAttributes(typeof(SubmitMethodAttribute), false) as SubmitMethodAttribute[]
                         where a.Length > 0
                         select new MethodInvokeInfo
                         {
                             MethodInfo = m,
                             MethodAttribute = a[0]
                         }).ToArray<MethodInvokeInfo>();
                CustomPageAdapter.methodTable[type.ToString()] = array;
            }
            return array;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (base.Page.Request.Form.AllKeys.Length != 0)
            {
                MethodInvokeInfo[] methodInfo = CustomPageAdapter.GetMethodInfo(base.Page.GetType().BaseType);
                if (methodInfo.Length != 0)
                {
                    foreach (MethodInvokeInfo methodInvokeInfo in methodInfo)
                    {
                        if (base.Page.Request.Form.AllKeys.Contains(methodInvokeInfo.MethodInfo.Name))
                        {
                            methodInvokeInfo.MethodInfo.Invoke(base.Page, null);
                            if (methodInvokeInfo.MethodAttribute.AutoRedirect && !base.Page.Response.IsRequestBeingRedirected)
                            {
                                base.Page.Response.Redirect(base.Page.Request.RawUrl);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }
}